import router from './router'
import * as LoginApi from '@/api/login'
import * as authUtil from '@/utils/auth'
import type { RouteRecordRaw } from 'vue-router'
import { getAccessToken } from '@/utils/auth'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()
// 路由不重定向白名单
const whiteList = [
  '/login',
  '/loginAdmin',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/oauthLogin/gitee',
  '/register',
  '/oauthLogin/gitee',
  '/submitSuccess',
  '/registerJump',
  '/queryProgress'
]

const getFullPath = (routers) => {
  const pathList: any[] = []
  const findPath = (routers, ppath = '') => {
    routers.forEach((e) => {
      if (e.children?.length) {
        const path = ppath
          ? `${ppath}/${e.path}`
          : `${ppath}${e.path}`
        findPath(e.children, path)
      } else {
        const path = ppath
          ? `${ppath}/${e.path}`
          : `${ppath}${e.path}`
        pathList.push(path)
      }
    })
  }
  findPath(routers)
  return pathList
}

const getTenantId = async () => {
  // const data = {
  //   domain: 'http://test.8ykj.cn/jingjiaAdmin/index.html'
  // }
  // const data = {domain: 'http://test.8ykj.cn/jingjia/index.html'}
  const data = {
    domain: `${location.origin}${location.pathname}`
  }
  const res = await LoginApi.getTenantIdByDomain(data)
  authUtil.setTenantId(res)
}

//路由加载前
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  if (getAccessToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 获取所有字典
      const dictStore = useDictStoreWithOut()
      const userStore = useUserStoreWithOut()
      const permissionStore = usePermissionStoreWithOut()
      // 查看是否设置字典
      if (!userStore.getIsSetUser) {
        try {
          await getTenantId()
          await userStore.setUserInfoAction()
          await permissionStore.generateRoutes()
        } catch {
          next()
        }
        // 后端过滤菜单
        permissionStore.getAddRouters.forEach(
          async (route) => {
            router.addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
          }
        )
        const dynamicRouter =
          permissionStore.getDynamicRouter
        if (dynamicRouter.length) {
          const pathList = getFullPath(dynamicRouter)
          if (to.path === '/') {
            next({ path: pathList[0] })
          } else {
            next({ path: to.path, query: to.query })
          }
        } else {
          next({ path: '/403' })
        }
      } else {
        next()
      }
      if (!dictStore.getIsSetDict) {
        try {
          await dictStore.setDictMap()
        } finally {
          next()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      try {
        await getTenantId()
      } finally {
        next()
      }
    } else {
      try {
        await getTenantId()
      } finally {
        next(`/login`)
      }
    }
  }
})

router.afterEach(() => {
  // useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
